package com.school.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Druid 数据源配置
 */
@Configuration
public class DruidConfig {
    
    @Value("${spring.datasource.url}")
    private String url;
    
    @Value("${spring.datasource.username}")
    private String username;
    
    @Value("${spring.datasource.password}")
    private String password;
    
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    
    /**
     * 配置Druid数据源
     */
    @Bean
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSource druidDataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        // 设置基本配置
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }
    
    /**
     * 配置Druid监控页面
     */
    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(
                new StatViewServlet(), "/druid/*");
        
        Map<String, String> initParams = new HashMap<>();
        // 监控页面登录用户名
        initParams.put("loginUsername", "admin");
        // 监控页面登录密码
        initParams.put("loginPassword", "admin");
        // IP白名单（为空或null表示允许所有访问）
        initParams.put("allow", "");
        // IP黑名单（存在共同时，deny优先于allow）
        initParams.put("deny", "");
        // 禁用HTML页面上的"Reset All"功能
        initParams.put("resetEnable", "false");
        
        bean.setInitParameters(initParams);
        return bean;
    }
    
    /**
     * 配置Druid Web监控过滤器
     */
    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilter() {
        FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>(new WebStatFilter());
        
        Map<String, String> initParams = new HashMap<>();
        // 排除不需要监控的资源
        initParams.put("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        
        bean.setInitParameters(initParams);
        // 拦截所有请求
        bean.addUrlPatterns("/*");
        return bean;
    }
}

